#!/usr/bin/python
#encoding=utf-8
'''
This script is for batch download music from http://mp3.baidu.com
'''
import logging
import os
import re
import urllib
import sys

# download directory
file_path = '/home/justin/Music'
################## for Western Music #################
# music category
#url = "http://list.mp3.baidu.com/list/oumei.html"
#music_list_patten = r'<a href="(http://mp3.baidu.com/m\?tn=baidump3&ct=134217728&lm=-1&li=\d+&word=.*?)" target=_blank>\s*(.*?)\s*</a>'
################## for Top 500 Music ##################
url = "http://list.mp3.baidu.com/topso/mp3topsong.html?id=1?top2"
music_list_patten = r'<a href="(http://mp3.baidu.com/m\?tn=baidump3&ct=134217728&lm=-1&li=\d+&word=.*?)" target=_blank><b>\s*(.*?)\s*</b></a>'
################## else ###############################
# music file type
type_dict = {'baidu_type': '0', 'suffix': 'mp3'}

music_url_proxy_patten = r'<a href="(.*?)" title="请点击左键'
music_url_proxy_patten = music_url_proxy_patten.decode('utf-8').encode('gb2312')

music_url_patten = r'<a href="(.*?)" target="_blank">'
music_url_patten = music_url_patten.decode('utf-8').encode('gb2312')

def getLogger():
    logger = logging.getLogger('batch_download')
    hdlr = logging.FileHandler('/tmp/batch_download_log')
    formatter = logging.Formatter('%(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    logger.propagate = 0
    return logger

logger = getLogger()

def main():
    #import pdb; pdb.set_trace()
    html = ''.join(urllib.urlopen(url))
    music_list_url_list = re.findall(music_list_patten, html)
    file_list = os.listdir(file_path)
    for music_list_url, name in music_list_url_list:
        name = '%s.%s' % (name.decode('gb2312').encode('utf-8').replace(' ', '_'), type_dict['suffix'])
        name = name.lower()
        if name in file_list:
            continue
        music_list_url = music_list_url.replace('lm=-1', 'lm=%s' % type_dict['baidu_type'])
        html = ''.join(urllib.urlopen(music_list_url))
        music_url_proxy_obj = re.search(music_url_proxy_patten, html)
        if music_url_proxy_obj:
            # for the url contains space, browser can work with it, but noy urllib
            music_url_proxy = music_url_proxy_obj.group(1).replace(' ', '%20')
            html = ''.join(urllib.urlopen(music_url_proxy))
            music_url_obj = re.search(music_url_patten, html)
            if music_url_obj:
                music_url = music_url_obj.group(1)
                os.system('wget -t 1 -O /home/justin/Music/%s "%s"' % (name, urllib.unquote_plus(music_url)))
            else:
                logging.error("No music %s" % name)
        else:
            logging.error("No music %s" % name)

if __name__ == '__main__':
    try:
        logging.info('start')
        main()
        logging.info('end')
    except Exception, e:
        logging.error(e)
